const ObjectID = require('mongodb').ObjectID;
const async = require('async');
const orderCode = require('yi-order-number');

module.exports = {
    open: false,
    description: '直接购买商品结算价格',
    handler(req, res, next) {
        const doc = req.body;
        req.mongo.collection('goods').findOne({_id: doc.goodsId,storeId:doc.storeId}, (e0, goods) => {
            if (e0 || !goods) {
                return res.reply({code: 10001, message: '商品信息异常请重试'});
            } else {
                let amount = goods.actualPrice * doc.buyCount; //商品金额

                let authInfo = req.context || req.context.authInfo;
                if (!req.context || !req.context.authInfo) {
                    return res.err.unauthorized();
                }
                authInfo = authInfo.authInfo;
                let userId = ObjectID(authInfo._id);

                req.mongo.collection('coupon').find({userId:userId,minPrice:{$lte:amount}}).toArray((e1,r1)=>{
                    if(e1) return res.err.mongoError(e1);
                    if(r1.length>0) {
                        let couponArr = [];
                        r1.forEach((coupon)=>{
                            coupon.storeIds.forEach((storeId)=>{
                                if(storeId.toString()===doc.storeId.toString()) couponArr.push(coupon);
                            });
                        });
                        goods.couponCount = couponArr.length;
                        goods.couponArr = couponArr;
                    }else{
                        goods.couponCount = 0;
                    }
                    goods.buyCount = doc.buyCount;
                    goods.amount = amount;
                    return res.reply({code:0,message:'商品结算',data:goods});
                });
            }
        });
    }
};